﻿using System;
using System. Linq;
using System. Net;
using System. Windows;
using System. Windows. Data;
using System. Xml. Linq;
using Microsoft. Phone. Controls;
using Microsoft. Phone. Shell;
using Microsoft. Phone. Tasks;
using NextApp. WP7. AppConfig;
using NextApp. WP7. Models;
using WP7_ControlsLib. Controls;
using NextApp. WP7. Util;
using System. Text. RegularExpressions;
using NextApp. WP7. Cache. NextApp;

namespace NextApp. WP7. View
{
    public partial class PostDetail : PhoneApplicationPage
    {
        #region Initialize
        public PostDetail( )
        {
            InitializeComponent( );
			this. PrepareToOrientation( );
            this. pivot. Title = Config. Instance. blog_title;
            this. Loaded += new RoutedEventHandler(PostDetail_Loaded);
            EventSingleton. Instance. OnRefreshComments += (s, e) =>
                {
                    if ( (s as Controls.CommentList) == this.comments)
                    {
                        if ( this.postID != 0 )
                        {
                            this. comments. Reload(true, this. postID, 0, true);
                        }
                    }
                };
        }
        private int postID { get; set; }
        private Post post { get; set; }
        protected override void OnNavigatedTo(System. Windows. Navigation. NavigationEventArgs e)
        {
            //登入注销处理
            Util. Tool. CheckAppBar(this);
            //处理PostID
            this. Receive_PostID( );
            //处理Portal
            this. Receive_Portal( );

            base. OnNavigatedTo(e);
        }
        public void Reload( )
        {
			WebClient client = Util. Tool. GetWebClient;
            client. DownloadStringCompleted += (s, e1) =>
            {
				CacheNextApp. Instance. MinusBandwidthCost(new BandwidthCostNextApp { cost = BandwidthCostNextApp. Post_Detail });
                if ( e1. Error != null )
                {
                    MessageBox. Show("获取文章详情发生错误", "网络错误", MessageBoxButton. OK);
                    return;
                }
				XElement postElement;
				try
				{
					postElement = XElement. Parse(e1. Result). Element("post");
				}
				catch ( Exception )
				{
					return;
				}
                Post post = new Post
                {
                    id = postElement. Element("id"). Value. ToInt32( ),
                    catalog = postElement. Element("catalog"). Value. Split(','). ToArray( ). Select(c => c. ToInt32( )). ToArray( ),
                    title = postElement. Element("title"). Value,
                    url = postElement. Element("url"). Value,
                    body = postElement. Element("body"). Value,
                    tags = postElement. Element("tags"). Value. Split(','),
                    author = postElement. Element("author"). Value,
                    pubDate = postElement. Element("pubDate"). Value,
                    commentCount = postElement. Element("commentCount"). Value. ToInt32( ),
                    relativePosts = postElement. Element("relativePosts") == null ?
                                            null :
                                            postElement. Element("relativePosts"). Elements("relativePost"). Select(
                                            r => new RelativePost
                                            {
                                                id = r. Element("id"). Value. ToInt32( ),
                                                author = r. Element("author"). Value,
                                                pubDate = r. Element("pubDate"). Value,
                                                title = r. Element("title"). Value,
                                            }
                                        ). ToArray( ),
                };
                //测试获取整篇详细文章成功               
                DataSingleton. Instance. postToShare = post;
                this. Grid_Post. Visibility = System. Windows. Visibility. Visible;
                this. post = post;
                this. ProgressIndicatorIsVisible = false;
                this. Grid_Post. DataContext = post;
				string bodyResult;
				try
				{
					bodyResult = Util. Tool. ProcessHTMLString(post. body);
				}
				catch ( Exception ex)
				{
					bodyResult = post. body;
					System. Diagnostics. Debug. WriteLine("获取文章详情失败: {0}", ex. Message);
				}
				//这里要进行 HTML 中文转码
				bodyResult = ControlHelper. ConvertExtendedASCII(bodyResult);
				this. browser. NavigateToString(bodyResult);
                //分配相关文章到第3个 Tab
                this. relativePosts. SetDatas(post. relativePosts);
            };
            //异步获取文章详情
            if ( NextAppSingleton. Instance. url_post_detail. IsNotNullOrWhitespace( ) )
            {
                client. DownloadStringAsync(new Uri(Config. Instance. GetApi(string. Format("{0}&post={1}&guid={2}", NextAppSingleton. Instance. url_post_detail, postID, Guid.NewGuid())), UriKind. Absolute));
				CacheNextApp. Instance. AddBandwidthCost(new BandwidthCostNextApp { cost = BandwidthCostNextApp. Post_Detail });
				this. ProgressIndicatorIsVisible = true;
            }
        }
        #endregion

        #region 回到上一页
        private void icon_GoBack_Click(object sender, EventArgs e)
        {
            if ( this. NavigationService. CanGoBack )
            {
                this. NavigationService. GoBack( );
            }
            else
            {
                this. NavigationService. Navigate(new Uri("/MainPage.xaml", UriKind. Relative));
            }
        }
        #endregion

        #region 增加/刷新 评论
        private void icon_AddComment_Click(object sender, EventArgs e)
        {
            this. NavigationService. Navigate(new Uri(string. Format("/View/AddComment.xaml?post={0}", postID), UriKind. Relative));
        }
        private void icon_RefreshComment_Click(object sender, EventArgs e)
        {
            this. comments. Reload(true, this. postID, 0, true);
        }
        #endregion

        #region 进入分享页面
        private void icon_SharePost_Click(object sender, EventArgs e)
        {
            switch ( this.pivot.SelectedIndex )
            {
                case 0:
                    DataSingleton. Instance. GoToSharePageType = GoToSharePageType. PostDetail;
                    break;
                case 1:
                    DataSingleton. Instance. GoToSharePageType = GoToSharePageType. Comments;
                    break;
                case 2:
                    DataSingleton. Instance. GoToSharePageType = GoToSharePageType. RelativePosts;
                    break;
            }
            this. NavigationService. Navigate(new Uri("/View/Share.xaml", UriKind. Relative));
        }
        #endregion

        #region 将文章订到桌面上
        private void menuItem_PinToStart_Click(object sender, EventArgs e)
        {
            if ( this.post != null )
            {
                Util. Tool. CreateShellTile(this. post);
            }
        }
        #endregion

        #region 在IE9中查看该文章
        private void menuItem_ViewInBrowser_Click(object sender, EventArgs e)
        {
            WebBrowserTask task = new WebBrowserTask { Uri = new Uri(this. post. url, UriKind. Absolute) };
            task. Show( );
        }
        #endregion

        #region 处理PostID
        private void Receive_PostID( )
        {
            if ( this. NavigationContext. QueryString. ContainsKey("post") )
            {
                this. postID = this. NavigationContext. QueryString[ "post" ]. ToInt32( );
                this. comments. postID = postID;
                this. comments. Reload(true, postID);

                //加载数据
                this. Reload( );
            }
        }
        #endregion

        #region 处理页面入口模式
        private void Receive_Portal( )
        {
            if ( this.NavigationContext.QueryString.ContainsKey("portal") )
            {
                switch ( this.NavigationContext.QueryString["portal"] )
                {
                    case "PostDetail":
                        this. pivot. SelectedIndex = 0;
                        break;
                    case "Comments":
                        this. pivot. SelectedIndex = 1;
                        break;
                    case "RelativePosts":
                        this. pivot. SelectedIndex = 2;
                        break;
                }
            }
        }
        #endregion

        #region 进度条
        private void PostDetail_Loaded(object sender, RoutedEventArgs e)
        {
            SystemTray. ProgressIndicator = new ProgressIndicator( );
            SystemTray. ProgressIndicator. Text = "加载中";

            Binding bindingData;
            bindingData = new Binding("ProgressIndicatorIsVisible");
            bindingData. Source = this;
            BindingOperations. SetBinding(SystemTray. ProgressIndicator, ProgressIndicator. IsVisibleProperty, bindingData);
            BindingOperations. SetBinding(SystemTray. ProgressIndicator, ProgressIndicator. IsIndeterminateProperty, bindingData);
        }
        public static readonly DependencyProperty ProgressIndicatorIsVisibleProperty =
            DependencyProperty. Register("ProgressIndicatorIsVisible",
            typeof(bool),
            typeof(PostDetail),
            new PropertyMetadata(false));

        public bool ProgressIndicatorIsVisible
        {
            get { return ( bool )GetValue(ProgressIndicatorIsVisibleProperty); }
            set { SetValue(ProgressIndicatorIsVisibleProperty, value); }
        }
        #endregion

        #region 登入注销处理
        //登入
        private void menuItem_Login_Click(object sender, EventArgs e)
        {
            Util. Tool. Login( );
        }

        //注销
        private void menuItem_Logout_Click(object sender, EventArgs e)
        {
            Util. Tool. Logout( );
            Util. Tool. CheckAppBar(this);
        }
        #endregion
    }
}